package cn.edu.scau.serviceImpl;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import cn.edu.scau.dao.WorkDao;
import cn.edu.scau.entity.Work;
import cn.edu.scau.service.WorkService;

/**
 * 学术比赛的业务逻辑层（to do）
 * 
 * @author cxywan
 *
 */
@Service("workServiceImpl")
public class WorkServiceImpl implements WorkService<Work> {

	/**
	 * 持久化层
	 */
	@Autowired
	private WorkDao workDao;

	public WorkDao getWorkDao() {
		return workDao;
	}

	public void setWorkDao(WorkDao workDao) {
		this.workDao = workDao;
	}

	/**
	 * 保存实体
	 * 
	 * @param entity
	 *            Work 实体
	 * 
	 */
	@Override
	public void add(Work entity) {
		// 保存实体
		this.getWorkDao().save(entity);
	}

	/***
	 * 删除实体
	 * 
	 * @param entity
	 *            Work 实体
	 * 
	 */
	public boolean delete(Work entity, Integer id) {

		if (this.getWorkDao().find(Work.class, id) != null) {
			this.getWorkDao().delete(entity);
			return true;
		}
		return false;

	}

	/**
	 * 根据id删除实体
	 * 
	 * @param id
	 *            Work id
	 * 
	 */
	@Override
	public boolean delete(Integer id) {
		if (this.getWorkDao().find(Work.class, id) != null) {
			this.getWorkDao().delete(Work.class, id);
			return true;
		}
		return false;
	}

	/**
	 * 更新实体
	 * 
	 * @param entity
	 *            Work 实体
	 * 
	 */
	@Override
	public boolean update(Work entity, Integer id) {
		if (this.getWorkDao().find(Work.class, id) != null) {
			this.getWorkDao().update(entity);
			return true;
		}
		return false;
	}

	/**
	 * 根据id获取实体
	 */
	@Override
	public Work getWorkByID(Integer id) {

		return this.getWorkDao().find(Work.class, id);
	}

	/**
	 * 前后台获取页面总数
	 * 
	 * @param columnID
	 *            栏目ID
	 * @param pageSize
	 *            每一页要展示的条目总数
	 * @param frontOrBack
	 *            前台还是后台获取
	 */
	public long countTheEntityNum(Integer columnID, Integer pageSize, boolean frontOrBack) {

		Long count = (long) 0;
		if (frontOrBack) {

			count = this.getWorkDao().findCountByColumnIDFront(columnID);
			System.out.println(count);
		} else {
			count = this.getWorkDao().findCountByColumnIDManagement(columnID);
			System.out.println(count);
		}

		return count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
	}

	/**
	 * 获取前后或者后台的work属性
	 * 
	 * @param columnID
	 *            栏目ID
	 * @param pageNO
	 *            第几页
	 * @param pageSize
	 *            每一页要展示的条目总数
	 * @param frontOrBack
	 *            前台还是后台获取
	 */
	public List getPropertyOfWork(Integer columnID, Integer page, Integer pageSize, Boolean frontOrBack) {

		if (frontOrBack) {
			return this.getWorkDao().getPropertyOfWorkFront(columnID, page, pageSize);
		} else {
			return this.getWorkDao().getPropertyOfWorkManagement(columnID, page, pageSize);
		}

	}

	/**
	 * 返回所有学术相关的实体总数
	 */
	public Long findWorkAllCount() {

		return this.getWorkDao().findCount(Work.class);
	}

	/**
	 * 保存头像
	 * 
	 * @param file
	 *            头像
	 * @param fileName
	 *            头像名
	 * @param path
	 *            头像保存地址
	 */
	public List<String> saveImage(MultipartFile[] files, HttpServletRequest request, String releaseDate) {

		// 新建集合,用于保存文件路径和名称
		List<String> images = new ArrayList<>();
		// 获得顶级文件夹路径
		String path = request.getSession().getServletContext().getRealPath("/Upload/");
		// 获取纯数字的日期
		String date = getDate(releaseDate, 2);
		// 组合文件夹的名称
		String dirName = "day_" + date;
		// 循环保存上传的文件
		for (int i = 0; i < files.length; i++) {

			// 文件的后缀名称
			String suffix = files[i].getOriginalFilename().substring(files[i].getOriginalFilename().lastIndexOf('.'));

			System.out.println(suffix);
			// 组合图像的名称
			String fileName = date + this.getRandomString(10) + suffix;
			// 将图片保存路径放到集合中
			images.add("/Upload/" + dirName + "/" + fileName);
			// 新建一个文件
			File targetFile = new File(path + dirName + "/", fileName);
			// 如果文件夹不存在，则新建文件夹
			if (!targetFile.exists()) {
				targetFile.mkdirs();
			}
			// 保存人物头像
			try {
				files[i].transferTo(targetFile);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return images;

	}

	/**
	 * 根据日期，获取保存文件夹的名字
	 *
	 * @return
	 */
	public String getDate(String releaseDate, int start) {

		char[] chs = releaseDate.toCharArray();
		StringBuilder builder = new StringBuilder();

		for (int i = start; i < chs.length; i++) {

			if (chs[i] == ' ') {
				break;
			}

			if (chs[i] >= '0' && chs[i] <= '9') {
				builder.append(chs[i]);
			}
		}
		return new String(builder);
	}

	/**
	 * 获取随机字符串，用于组成图片的名字
	 * 
	 * @param length
	 * @return
	 */
	public static String getRandomString(int length) { // length表示生成字符串的长度
		String base = "012345678901234567890123456789";
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		return sb.toString();
	}

	@Override
	public List showTheEntity(String type, Integer columnId, Integer id, Integer pageNo, boolean frontOrBackground) {
		// TODO Auto-generated method stub
		return null;
	}

}
